package com.atlas.alpha;

import android.content.*;
import android.database.*;
import android.database.sqlite.*;

public class LoginDataBaseAdapter {
	static final String DATABASE_NAME = "login.db";
	static final int DATABASE_VERSION = 1;
	static final String DATABASE_CREATE = "create table " + "LOGIN" + "( "
			+ "ID" + " integer primary key autoincrement,"
			+ "USERNAME  text,PASSWORD text); ";
	public SQLiteDatabase db;
	private final Context context;
	private DataBaseHelper dbhelper;

	public LoginDataBaseAdapter(Context newContext) {
		context = newContext;
		dbhelper = new DataBaseHelper(context, DATABASE_NAME, null,
				DATABASE_VERSION);
	}

	public LoginDataBaseAdapter open() throws SQLException {
		db = dbhelper.getWritableDatabase();
		return this;
	}

	public void close() {
		db.close();
	}

	public SQLiteDatabase getDBInstance() {
		return db;
	}

	/*
	 * function accepts username/password strings and inserts them into new row
	 * in the table.
	 */
	public void addUser(String desiredUserName, String password) {
		ContentValues newValues = new ContentValues();
		newValues.put("USERNAME", desiredUserName);
		newValues.put("PASSWORD", password);
		db.insert("LOGIN", null, newValues);
	}

	public int deleteUser(String userName) {
		String where = "USERNAME=?";
		return db.delete("LOGIN", where, new String[] { userName });
	}

	public String getUserPass(String userName) {
		Cursor cursor = db.query("LOGIN", null, " USERNAME=?", 
				new String[] { userName }, null, null, null);
		//make sure the username is found
		if (cursor.getCount() < 1) {
			cursor.close();
			return "NOT EXIST";
		}
		//move cursor to first row
		cursor.moveToFirst();
		//get string in the users' PASSWORD column
		String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
		cursor.close();
		return password;
	}
}
